package cn.com.xyc.datasource.dao.impl;

import java.util.List;

import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import cn.com.xyc.datasource.dao.UserDao;
import cn.com.xyc.datasource.pojo.User;

public class HibernateUserDao extends HibernateDaoSupport implements UserDao {

	/**
	 * 如果不继承HibernateDaoSupport可以添加属性
	 */
/*	private HibernateTemplate template;

	public void setTemplate(HibernateTemplate template) {
		this.template = template;
	}*/

	@Override
	public void save(User user) {
		this.getHibernateTemplate().save(user);

	}

	@Override
	public void update(User user) {
		this.getHibernateTemplate().update(user);

	}

	@Override
	public void deleteById(int id) {
		User user = findById(id);
		this.getHibernateTemplate().delete(user);

	}

	@Override
	public User findById(int id) {
		String hql = "from User user where user.id=?";
		List list = this.getHibernateTemplate().find(hql, new Object[] { id });
		if (!list.isEmpty()) {
			return (User) list.get(0);
		}
		return null;
	}

	@Override
	public List<User> findAll() {
		String hql = "from User";
		return (List<User>) this.getHibernateTemplate().find(hql);
	}

	@Override
	public int count() {
		String hql = "select count(*) from User";
		List list = this.getHibernateTemplate().find(hql);
		return Integer.parseInt(list.get(0).toString());
	}

}
